from flask import Blueprint, jsonify, request
from flask_jwt_extended import jwt_required, get_jwt_identity
from app.models.Skillc2 import User, BalanceRecord
from app import db
from datetime import datetime

balance_bp = Blueprint('balance', __name__)

@balance_bp.route('/balance', methods=['GET'])
@jwt_required()
def get_balance():
    """查询用户余额"""
    try:
        current_user_id = int(get_jwt_identity())
        user = User.query.filter_by(UserId=current_user_id).first()
        
        if not user:
            return jsonify({
                'status': 'error',
                'message': '用户不存在'
            }), 404

        return jsonify({
            'status': 'success',
            'data': {
                'balance': float(user.UserBalance or 0)
            }
        })

    except Exception as e:
        return jsonify({
            'status': 'error',
            'message': str(e)
        }), 500

@balance_bp.route('/balance/add', methods=['POST'])
@jwt_required()
def add_balance():
    """增加用户余额"""
    try:
        current_user_id = int(get_jwt_identity())
        data = request.get_json()

        if not data or 'amount' not in data or 'description' not in data:
            return jsonify({
                'status': 'error',
                'message': '缺少必要的字段'
            }), 400

        amount = float(data['amount'])
        description = data['description']

        if amount <= 0:
            return jsonify({
                'status': 'error',
                'message': '金额必须大于0'
            }), 400

        user = User.query.filter_by(UserId=current_user_id).first()
        if not user:
            return jsonify({
                'status': 'error',
                'message': '用户不存在'
            }), 404

        # 创建余额记录
        balance_record = BalanceRecord(
            UserId=current_user_id,
            Amount=amount,
            Description=description,
            CreateTime=datetime.now()
        )

        # 更新用户余额
        user.UserBalance = (user.UserBalance or 0) + amount
        
        db.session.add(balance_record)
        db.session.commit()

        return jsonify({
            'status': 'success',
            'message': '余额增加成功',
            'data': {
                'current_balance': float(user.UserBalance),
                'amount': amount,
                'description': description,
                'create_time': balance_record.CreateTime.strftime('%Y-%m-%d %H:%M:%S')
            }
        })

    except Exception as e:
        db.session.rollback()
        return jsonify({
            'status': 'error',
            'message': str(e)
        }), 500

@balance_bp.route('/balance/reduce', methods=['POST'])
@jwt_required()
def reduce_balance():
    """减少用户余额"""
    try:
        current_user_id = int(get_jwt_identity())
        data = request.get_json()

        if not data or 'amount' not in data or 'description' not in data:
            return jsonify({
                'status': 'error',
                'message': '缺少必要的字段'
            }), 400

        amount = float(data['amount'])
        description = data['description']

        if amount <= 0:
            return jsonify({
                'status': 'error',
                'message': '金额必须大于0'
            }), 400

        user = User.query.filter_by(UserId=current_user_id).first()
        if not user:
            return jsonify({
                'status': 'error',
                'message': '用户不存在'
            }), 404

        # 检查余额是否足够
        if (user.UserBalance or 0) < amount:
            return jsonify({
                'status': 'error',
                'message': '余额不足'
            }), 400

        # 创建余额记录
        balance_record = BalanceRecord(
            UserId=current_user_id,
            Amount=-amount,  # 负数表示减少
            Description=description,
            CreateTime=datetime.now()
        )

        # 更新用户余额
        user.UserBalance = user.UserBalance - amount
        
        db.session.add(balance_record)
        db.session.commit()

        return jsonify({
            'status': 'success',
            'message': '余额减少成功',
            'data': {
                'current_balance': float(user.UserBalance),
                'amount': amount,
                'description': description,
                'create_time': balance_record.CreateTime.strftime('%Y-%m-%d %H:%M:%S')
            }
        })

    except Exception as e:
        db.session.rollback()
        return jsonify({
            'status': 'error',
            'message': str(e)
        }), 500

@balance_bp.route('/balance/history', methods=['GET'])
@jwt_required()
def get_balance_history():
    """查询用户余额变动历史"""
    try:
        current_user_id = int(get_jwt_identity())
        page = request.args.get('page', 1, type=int)
        per_page = request.args.get('per_page', 10, type=int)

        user = User.query.filter_by(UserId=current_user_id).first()
        if not user:
            return jsonify({
                'status': 'error',
                'message': '用户不存在'
            }), 404

        records = BalanceRecord.query.filter_by(UserId=current_user_id)\
            .order_by(BalanceRecord.CreateTime.desc())\
            .paginate(page=page, per_page=per_page)

        return jsonify({
            'status': 'success',
            'data': {
                'total': records.total,
                'pages': records.pages,
                'current_page': page,
                'per_page': per_page,
                'records': [record.to_dict() for record in records.items]
            }
        })

    except Exception as e:
        return jsonify({
            'status': 'error',
            'message': str(e)
        }), 500
